package com.woniuxy.spring;

import com.woniuxy.Person;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

//bean工厂 多例
public class BeanFactory2 {
    //定义一个Properties对象
    static Properties properties = new Properties();

    //定义一个Map,用于存放我们要创建的对象  容器
    static Map<String, Person> map = new HashMap<>();

    //使用静态代码块为Properties对象赋值
    static {
        //1.读取配置文件
        //properties = new Properties();
        //2.获取一个inputStream
        InputStream resourceAsStream = BeanFactory2.class.getResourceAsStream("beans.properties");
        //3.读取配置文件
        try {
            properties.load(resourceAsStream);
            //实例化容器
            //map = new HashMap<String,Person>();
            //4.获取配置文件中所有的key
            for(String key : properties.stringPropertyNames()){
                //遍历后的key，来获取对应的value，这个value就是个全限定类名
                String property = properties.getProperty(key);
                System.out.println(property+"......");
                Person person = (Person) Class.forName(property).newInstance();
                map.put(key,person);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    public Person getBean(String name){
        Person person = null;
        try {
            String property = properties.getProperty(name);
            System.out.println(property+"======");
            person = (Person) Class.forName(property).newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return person;
    }
}
